import { defineStore } from "pinia";
import { constantRoutes } from "@/router";
import Layout from "@/layout/index.vue";
const modules = import.meta.glob("./../views/**/*.vue")

const usePermissionStore = defineStore("permission", {
  state: () => ({
    sidebarRouters: []
  }),
  actions: {
    generateRoutes (roles) {
      return new Promise(resolve => {
        // 模拟后端接口返回的路由数据

        const res = {
          data: [
            {
              "name": "System",
              "path": "/system",
              "hidden": false,
              "redirect": "noRedirect",
              "component": "Layout",
              "alwaysShow": true,
              "meta": {
                "title": "系统管理",
                "icon": "system",
                "noCache": false,
                "link": null
              },
              "children": [
                {
                  "name": "User",
                  "path": "user",
                  "hidden": false,
                  "component": "system/user",
                  "meta": {
                    "title": "用户管理",
                    "icon": "user",
                    "noCache": false,
                    "link": null
                  }
                },
                {
                  "name": "Role",
                  "path": "role",
                  "hidden": false,
                  "component": "system/role",
                  "meta": {
                    "title": "角色管理",
                    "icon": "peoples",
                    "noCache": false,
                    "link": null
                  }
                }
              ]
            }
          ]
        }
        const sdata = JSON.parse(JSON.stringify(res.data))
        const rdata = JSON.parse(JSON.stringify(res.data))
        const sidebarRoutes = filterAsyncRouter(sdata)
        const rewriteRoutes = filterAsyncRouter(rdata, false, true)
        // 设置默认路由，router/index.js 中定义的constantRoutes，并与后台返回的动态路由进行合并
        this.sidebarRouters = constantRoutes.concat(sidebarRoutes);
        console.log("🚀 ~ getRouters ~ sidebarRoutes:", this.sidebarRouters, rewriteRoutes)
        resolve(rewriteRoutes)
      })
    }
  }
})

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter (asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter(route => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren (childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView' && !lastRouter) {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
      if (el.children && el.children.length) {
        children = children.concat(filterChildren(el.children, el))
        return
      }
    }
    children = children.concat(el)
  })
  return children
}

export const loadView = (view) => {
  let res;
  for (const path in modules) {
    const dir = path.split('views/')[1].split('.vue')[0];
    if (dir === view) {
      res = () => modules[path]();
    }
  }
  // import("componets/layout/index.vue")
  return res;
}

export default usePermissionStore